package com.rz.htk.template.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.rz.core.exception.GlobalException;
import com.rz.htk.order.entity.Order;
import com.rz.htk.product.entity.Product;
import com.rz.htk.product.service.IProductService;
import com.rz.htk.template.entity.TemplateField;
import com.rz.htk.template.service.ExportService;
import com.rz.htk.template.service.ITemplateFieldService;
import org.apache.poi.hssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @ClassName TemplateServiceImpl
 * @Description 模板service实现类
 * @Author maweiyue
 * @Date 2019/4/17 20:37
 */
@Service
@Lazy
public class ExportServiceImpl implements ExportService {

    private static Logger logger = LoggerFactory.getLogger("ExpressCodeServiceImpl");

    @Resource
    private ITemplateFieldService templateFieldService;

    @Resource
    private IProductService productService;

    private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 导出文件
     * @param prdCode 产品编号
     * @param list 查询结果集
     * @param out 输入流对象
     */
    public void export(String prdCode, List<?> list, OutputStream out) {
        Product product = this.productService.getProductByCode(prdCode);
        if (product != null) {
            this.export(list, product.getApiOrderTemplate(), out);
        }
    }

    public void export(List<?> orderList, Integer tempId, OutputStream out) {
        List<TemplateField> fields = this.templateFieldService.listByTemplateId(tempId);
        try {
            HSSFWorkbook workbook = new HSSFWorkbook(); // 创建工作簿对象
            HSSFSheet sheet = workbook.createSheet("test"); // 创建工作表

            HSSFRow rowRowName = sheet.createRow(2); // 在索引2的位置创建行(最顶端的行开始的第二行)
            // 将列头设置到sheet的单元格中
            for (int n = 0; n < fields.size(); n++) {
                HSSFCell cellRowName = rowRowName.createCell(n); // 创建列头对应个数的单元格
                HSSFRichTextString text = new HSSFRichTextString(fields.get(n).getLable());
                cellRowName.setCellValue(text); // 设置列头单元格的值
            }

            // 将查询出的数据设置到sheet对应的单元格中
            for (int i = 0; i < orderList.size(); i++) {
                Object order = orderList.get(i);   // 遍历每个对象
                HSSFRow row = sheet.createRow(i + 3);   // 创建所需的行数
                for (int j = 0; j < fields.size(); j++) {
                    HSSFCell cell = row.createCell(j);   // 设置单元格的数据类型
                    TemplateField field = fields.get(j);
                    if (StringUtils.isNotEmpty(field.getName())) {
                        // 设置本单元格的值
                        Class<?> clazz = Order.class;

                        Method method = clazz.getMethod("get" + firstCharToUpper(field.getName()), null);
                        Object obj = method.invoke(order);
                        if (obj != null) {
                            if (obj instanceof LocalDateTime) {
                                cell.setCellValue(dateTimeFormatter.format((LocalDateTime)obj));
                            } else {
                                cell.setCellValue(obj.toString());
                            }
                        }
                    }
                }
            }
            workbook.write(out);
        } catch (NoSuchMethodException e) {
            logger.error(e.getMessage(), e);
            throw new GlobalException("ExportService -> export：" + e.getMessage());
        } catch (Exception e){
            logger.error(e.getMessage(), e);
        }
    }

    public String firstCharToUpper(String str){
        if (str == null || str.equals("")) {
            return "";
        }
        char[] chars = str.toCharArray();
        if (chars[0] >= 'a' && chars[0] <= 'z') {
            chars[0] = (char)(chars[0] - 32);
        }
        return new String(chars);
    }
}
